<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home ' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList"><el-button
              @click="getUserList" slot="append" icon="el-icon-search"></el-button></el-input></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table border :data="userList" style="width: 100%" stripe>
        <el-table-column type="index" label="#" width="180"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userstatechange(scope.row)" active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="showEditDialog(scope.row.id)" type="primary" icon="el-icon-edit"></el-button>
            <el-button type="danger" @click="open(scope.row.id)" icon="el-icon-delete"></el-button>
            <el-button type="warning" icon="el-icon-setting" @click="updata(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" align="center">
      </el-pagination>
      <!-- 添加用户的对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="ruleForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户的对话框 -->
      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
        <el-form :model="editDialog" :rules="rules" ref="editDialog" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input :disabled="true" v-model="editDialog.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editDialog.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editDialog.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="upeditDialog">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配列表 -->
      <el-dialog title="修改用户" :visible.sync="rughtDialogVisible" width="50%" height="400px">
        <div>
          <p>用户名 : {{ UserInfo.username }}</p>
          <p>角色名称 : {{ UserInfo.role_name }}</p>
          <el-select v-model="RoleUser" class="input-with-select">
            <el-option v-for="itme in RoleList" :label="itme.roleName" :key="itme.id" :value="itme.id"></el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rughtDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="rughtDialogVisibleDialog">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱规则
    const checkEmail = (rele, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 这是合法的邮箱
        console.log('12313')
        return cb()
      }
      cb(new Error('请输入合法邮箱'))
    }
    // 验证电话号码的规则
    const checkMobile = (rele, value, cb) => {
      // 验证手机的正则表达式
      const modile =
        /^(0|86|17951)?(13[0-9]|15[012345678]|17|678|18[0-9]|14[57])[0-9]{8}$/
      if (modile.test(value)) {
        // 这是合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法手机号'))
    }

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        // 用户名
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少调数据
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 分配列表对话框的显示与隐藏
      rughtDialogVisible: false,
      // 添加用户的表单数据
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editDialog: {},
      // 需要被分配的用户信息
      UserInfo: {},
      // 所有角色的数据列表
      RoleList: [],
      // 所选择的角色
      RoleUser: '',
      // 定义修改表单中的数据
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度不能超过10不能小于3',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 5,
            max: 10,
            message: '用户名长度不能超过10不能小于3',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户失败 !')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值
    handleCurrentChange(newCurrent) {
      this.queryInfo.pagenum = newCurrent
      this.getUserList()
    },
    // 监听switch 开关状态的改变
    async userstatechange(newtatechang) {
      console.log(newtatechang)
      const { data: res } = await this.$http.put(
        `users/${newtatechang.id}/state/${newtatechang.mg_state}`
      )
      if (res.meta.status !== 200) {
        newtatechang.mg_state = !newtatechang.mg_state
        return this.$message.error('更新用户状态失败')
      }
    },
    // 监听添加用户对话框的关闭事件
    addDialogClose() {
      this.$refs.ruleForm.resetFields()
    },
    // 点击按钮添加新用户
    addUser() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return this.$message.error('添加失败')
        // 可以发起添加用户
        const { data: res } = await this.$http.post('users', this.ruleForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message({
          message: '添加成功',
          type: 'success'
        })
        // 关闭添加弹窗
        this.addDialogVisible = false
        // 刷新列表
        this.getUserList()
      })
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        this.editDialogVisible = false
        return this.$message.error('查询用户信息失败')
      }
      this.editDialog = res.data
    },
    // 监听修改对话框是否关闭
    editDialogClose() {
      this.$refs.editDialog.resetFields()
    },
    upeditDialog() {
      this.$refs.editDialog.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editDialog.id,
          {
            email: this.editDialog.email,
            mobile: this.editDialog.mobile
          }
        )
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message({
          message: '修改成功',
          type: 'success'
        })
        // 刷新列表
        this.getUserList()
        this.editDialogVisible = false
      })
    },
    // 删除弹框
    async open(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 如果用户确认删除 则返回值为字符串 confirm
      // 如果取消了删除 则返回字符串 cancel
      if (confirmResult !== 'confirm') return this.$message.info('取消删除')
      console.log(id)
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message({
        message: '删除成功',
        type: 'success'
      })
      this.getUserList()
    },
    async rughtDialogVisibleDialog() {
      if (!this.RoleUser) return this.message.error('请选择要分配角色')
      const { data: res } = await this.$http.put(`users/${this.UserInfo.id}/role`, {
        rid: this.RoleUser
      })
      if (res.meta.status !== 200) return this.$message.error('分配失败')
      this.$message({
        message: '分配成功',
        type: 'success'
      })
      this.RoleUser = ''
      this.rughtDialogVisible = false
      this.getUserList()
    },
    async updata(rope) {
      this.UserInfo = rope
      this.rughtDialogVisible = true
      // 请求分配角色接口
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.message.error('获取列表失败')
      this.RoleList = res.data
    }
  }
}
</script>

<style lang='less' scoped></style>
